package com.geek.novel.fragment

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.os.Message
import android.view.Gravity
import android.view.MotionEvent
import android.view.View
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import com.geek.novel.R
import com.geek.novel.activity.book.ViewerActivity
import com.geek.novel.activity.main.MainActivity
import com.geek.novel.adapter.BaseRecyclerViewAdapter
import com.geek.novel.adapter.MyBookListAdapter
import com.geek.novel.bo.AppContext
import com.geek.novel.common.Constant
import com.geek.novel.dialog.MenuListDialog
import com.geek.novel.entity.BookRead
import com.geek.novel.listener.MenuItemInflaterViewListener
import com.geek.novel.services.BookRepository
import kotlinx.android.synthetic.main.fragment_my_book.*

/**
 * 我的书架页面
 */
class FragmentMyBook : BaseFragment() {

	/**菜单的弹出框*/
	private lateinit var menuListDialog: MenuListDialog

	/**当前长按选中的书籍的下标*/
	private var curBookSelectPosition = -1

	/**书籍列表*/
	private var books: ArrayList<BookRead> = ArrayList()

	/**书籍列表的适配器*/
	private lateinit var listViewAdapter: MyBookListAdapter

	/**书籍的service*/
	private var bookRepository = BookRepository.getInstance()

	override fun layoutId(): Int = R.layout.fragment_my_book
	override fun pageName(): String = AppContext.getContext().getString(R.string.title_bar_my_book)
	override fun fragmentName(): String = FragmentName
	
	@SuppressLint("ClickableViewAccessibility")
	override fun initV() {
		//初始化长按菜单的弹框
		this.initMenuListDialog()

		//初始化下拉刷新功能
		initRefreshLayout()

		//获取书籍列表
		this.queryBook()

		//添加适配器
		listViewAdapter = MyBookListAdapter(requireContext() as Activity, books)
		//排序书籍
		this.sortBookAdapter()

		lv_books.layoutManager = LinearLayoutManager(context)
		lv_books.adapter = listViewAdapter
		//列表项的点击事件
		listViewAdapter.onItemClickListener = object: BaseRecyclerViewAdapter.OnItemClickListener{
			override fun onItemClick(position: Int, event: MotionEvent?) {
				val book = books[position]
				//跳转到阅读页面
				val params = Bundle()
				params.putString("bookId", book.bookId)
				startActivityByAnim(requireContext(), ViewerActivity::class.java, params, Constant.ACTIVITY_RESULT_VIEWER)

				//置顶
				bookRepository.saveBookToTop(book)
			}
		}
		//列表项长按显示菜单
		listViewAdapter.onItemLongClickListener = object: BaseRecyclerViewAdapter.OnItemLongClickListener{
			override fun onItemLongClick(position: Int, event: MotionEvent?): Boolean {
				//记录下标
				curBookSelectPosition = position
				val book = getCurSelectBook()
				if(book != null){
					val name = if(book.top)"取消置顶" else "置顶"
					val key = Constant.KEY_MENUITEM_TOP
					val menuItem = MenuListDialog.MenuItem(key, name)
					menuListDialog.updateMenuItem(key, menuItem)
				}

				//打开菜单
				menuListDialog.openDialog(Gravity.NO_GRAVITY, event)
				return true
			}

		}

	}

	override fun onShow() {
		//获取书籍列表
		this.queryBook()
		//排序书籍
		this.sortBookAdapter()
	}

	override fun myClick(v: View) {
	}

	/**检查书籍列表是否为空*/
	private fun checkBookEmpty(): Boolean{
		//书架列表为空的情况，添加书籍按钮
		if(books.isEmpty()){
			ly_goto_add_book.visibility = View.VISIBLE
			btn_goto_add_book.setOnClickListener {
				(activity as MainActivity).pageToBookShop()
			}
		}else{
			ly_goto_add_book.visibility = View.GONE
		}
		return books.isEmpty()
	}

	/**获取书籍列表*/
	private fun queryBook(){
		val list = bookRepository.findAllBookshelf()
		books.clear()
		books.addAll(list)
		//检查书籍列表是否为空
		this.checkBookEmpty()
	}

	/**排序书籍*/
	private fun sortBookAdapter(){
		//按置顶和序号排序
		books.sortWith(Comparator.comparing<BookRead?, Int?> {
			if(it.top) -1 else 1
		}.thenComparator{o1, o2 ->
			o2.sort-o1.sort
		})
		listViewAdapter.notifyDataSetChanged()
	}

	/**删除书籍*/
	private fun deleteBook(){
		val curBook = getCurSelectBook()
		if(curBook != null){
			bookRepository.deleteBook(curBook)
			books.remove(curBook)
			listViewAdapter.notifyItemRemoved(this.curBookSelectPosition)

			//检查书籍列表是否为空
			this.checkBookEmpty()
		}
	}

	/**置顶书籍*/
	private fun topBook(){
		val curBook = getCurSelectBook()
		if(curBook != null){
			//置顶或者取消置顶
			if(!curBook.top){
				curBook.top = true
				//置顶书籍并保存
				bookRepository.saveBookToTop(curBook)
			}else{
				curBook.top = false
				bookRepository.save(curBook)
			}
			//刷新排序
			this.sortBookAdapter()
		}
	}

	/**获取当前书本*/
	private fun getCurSelectBook(): BookRead?{
		val pos = this.curBookSelectPosition
		if(pos > -1 && pos < books.size){
			return books[pos]
		}
		return null
	}

	/**菜单按钮点击的监听器*/
	inner class MenuItemClickListener: MenuListDialog.MenuItemClickListener{
		override fun onItemClick(item: MenuListDialog.MenuItem, view: View, position: Int): Boolean {
			when(item.key){
				//置顶书籍
				Constant.KEY_MENUITEM_TOP->{
					topBook()
				}
				//删除书籍
				Constant.KEY_MENUITEM_DELETE->{
					deleteBook()
				}
			}
			return true
		}
	}

	/**初始化长按菜单的弹框*/
	private fun initMenuListDialog(){
		val menuList = ArrayList<MenuListDialog.MenuItem>()
		menuList.add(MenuListDialog.MenuItem(Constant.KEY_MENUITEM_TOP, "置顶"))
		menuList.add(MenuListDialog.MenuItem(Constant.KEY_MENUITEM_DELETE, "删除"))
		//初始化弹框
		menuListDialog = MenuListDialog(requireContext(), R.layout.listview_menu_item, menuList)
		menuListDialog.inflaterViewListener = MenuItemInflaterViewListener()

		//绑定监听事件
		menuListDialog.onItemClickListener = MenuItemClickListener()
		//绑定事件之后，创建view
		menuListDialog.onCreateView()
	}

	/**
	 * 初始化下拉刷新功能
	 */
	private fun initRefreshLayout(){
		my_book_refresh_layout.setRefreshHeader(my_book_classics_header)
		my_book_refresh_layout.setEnableLoadMore(false)//不开启滚动加载
		my_book_refresh_layout.setOnRefreshListener { _ ->
			//刷新本地数据
			this.refreshLocalData()
			my_book_refresh_layout.finishRefresh(true)
		}
	}

	/**刷新本地数据*/
	private fun refreshLocalData(){
		//获取书籍列表
		this.queryBook()
		//刷新排序
		this.sortBookAdapter()
	}

	override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
		super.onActivityResult(requestCode, resultCode, data)
		when(requestCode){
			//从小说阅读页面返回的，刷新列表
			Constant.ACTIVITY_RESULT_VIEWER->{
				//刷新本地数据
				this.refreshLocalData()
			}
		}
	}

	/**处理观察者的事件*/
	override fun handleEvent(message: Message) {
		when(message.what){
			//更新我的书架页面的书籍列表
			Constant.handler_event_my_book_update_list->{
				//刷新本地数据
				this.refreshLocalData()
			}
		}
	}

	companion object {
		const val FragmentName = "FragmentMyBook"
		/**单例instance*/
		@SuppressLint("StaticFieldLeak")
		private var instance: FragmentMyBook? = null
		fun newInstance(): FragmentMyBook{
			if(instance == null){
				instance = FragmentMyBook()
			}
			return instance!!
		}
	}
	
}
